package com.gzdh.dishrecognition.ui.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.alibaba.fastjson.JSON;
import com.dhkj.web.bean.MacMainpFoodMenu;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.gzdh.dishrecognition.R;

public class FoodsEditFragment extends DialogFragment {

    private static final String TAG = "FoodsEditFragment";
    private Context mContext;

    private Long id;

    private String name = "";

    private String price = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        setRetainInstance(true);
        if (getArguments() != null) {
            String string = getArguments().getString("foodMenu");
            MacMainpFoodMenu foodMenu = JSON.parseObject(string, MacMainpFoodMenu.class);
            id = foodMenu.getId();
            name = foodMenu.getName();
            price = foodMenu.getPrice();
        }
//        systemSettingObject = getArguments().getParcelable(SystemSettingDialogFragment.SYSTEM_SETTING);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = inflater.getContext();
        View view = getViews();
        getDialog().getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                InputMethodManager manager = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (getDialog().getCurrentFocus() != null
                            && getDialog().getCurrentFocus().getWindowToken() != null) {
                        manager.hideSoftInputFromWindow(getDialog().getCurrentFocus()
                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                return false;
            }
        });
        return view;
    }

    private EditText userNameEd;

    private EditText passwordEd;

    private View getViews() {
        RelativeLayout.LayoutParams rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        LinearLayout mainLinear = new LinearLayout(mContext);
        mainLinear.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mainLinear.setOrientation(LinearLayout.VERTICAL);

        TextView textView = new TextView(mContext);
        rvParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        textView.setLayoutParams(rvParams);
        textView.setText("编辑菜品");
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        mainLinear.addView(textView);

        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mainLinear.addView(relativeLayout);

        LinearLayout linearLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(500, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(linearParams);
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setPadding(20, 30, 20, 30);
        relativeLayout.addView(linearLayout);

        //region 账号
        RelativeLayout userNameRv = new RelativeLayout(mContext);
        linearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearParams.setMargins(40, 20, 40, 0);
        userNameRv.setLayoutParams(linearParams);
        linearLayout.addView(userNameRv);

        View viewName = new View(mContext);
        viewName.setId(View.generateViewId());
        rvParams = new RelativeLayout.LayoutParams(5, 15);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.setMargins(10, 0, 0, 0);
        viewName.setLayoutParams(rvParams);
        viewName.setBackgroundColor(Color.rgb(200, 200, 200));
        userNameRv.addView(viewName);

        userNameEd = new EditText(mContext);
        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.setMargins(10, 0, 0, 0);
        rvParams.addRule(RelativeLayout.RIGHT_OF, viewName.getId());
        userNameEd.setLayoutParams(rvParams);
        userNameEd.setBackground(null);
        userNameEd.setHint("名称");
        userNameEd.setText(name);
        userNameEd.setEms(19);
        userNameEd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        userNameRv.addView(userNameEd);
        //endregion


        RelativeLayout passwordRv = new RelativeLayout(mContext);
        linearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearParams.setMargins(40, 20, 40, 0);
        passwordRv.setLayoutParams(linearParams);
        linearLayout.addView(passwordRv);


        View viewPassword = new View(mContext);
        viewPassword.setId(View.generateViewId());
        rvParams = new RelativeLayout.LayoutParams(5, 15);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.setMargins(10, 0, 0, 0);
        viewPassword.setLayoutParams(rvParams);
        viewPassword.setBackgroundColor(Color.rgb(200, 200, 200));
        passwordRv.addView(viewPassword);

        passwordEd = new EditText(mContext);
        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50);
        rvParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rvParams.setMargins(10, 0, 0, 0);
        rvParams.addRule(RelativeLayout.RIGHT_OF, viewPassword.getId());
        passwordEd.setLayoutParams(rvParams);
        passwordEd.setBackground(null);
        passwordEd.setHint("价格");
        passwordEd.setText(price);
        passwordEd.setEms(19);
        passwordEd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        passwordRv.addView(passwordEd);

        Button submitBut = new Button(mContext);

        rvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50);
        rvParams.setMargins(50, 0, 40, 40);
        submitBut.setText("确定");
        submitBut.setGravity(Gravity.CENTER);
        submitBut.setTextColor(Color.WHITE);
        submitBut.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        submitBut.setBackground(getResources().getDrawable(R.drawable.bg_btn_pay));
        linearLayout.addView(submitBut);
        submitBut.setOnClickListener(view -> preLogin());
        return mainLinear;
    }


    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    private void preLogin() {
        String name = userNameEd.getText().toString();
        String price = passwordEd.getText().toString();
        RequestUtils.foodsMenuAdd(mContext, name, price, new MyObserverRes<String>(mContext) {
            @Override
            public void onSuccess(String result) {
                dismiss();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                dismiss();
            }
        });

    }

    /**
     * 根据传入控件的坐标和用户的焦点坐标，判断是否隐藏键盘，如果点击的位置在控件内，则不隐藏键盘
     *
     * @param view  控件view
     * @param event 焦点位置
     * @return 是否隐藏
     */
    public static void hideKeyboard(MotionEvent event, View view, Activity activity) {
        try {
            if (view instanceof EditText) {
                int[] location = {0, 0};
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + view.getWidth(), bootom = top + view.getHeight();
                // （判断是不是EditText获得焦点）判断焦点位置坐标是否在控件所在区域内，如果位置在控件区域外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param view :一般为EditText
     */
    public static void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}
